<!DOCTYPE html>
<html>
<head>
  <link rel="chrome-webstore-item">
</head>
<body>
<script>
  function runTest(galleryUrl) {
    var downloadStarted = false;
    var installStarted = false;

    // Link URL has to be generated dynamically in order to include the right
    // port number. The ID corresponds to the data in the "extension" directory.
    document.getElementsByTagName('link')[0].href =
        galleryUrl + '/detail/ecglahbcnmdpdciemllbhojghbkagdje';

    try {
      chrome.webstore.onInstallStageChanged.addListener(function(stage) {
        if (stage == 'installing') {
          if (installStarted) {
            console.log('Received multiple "installing" stage events.');
            window.domAutomationController.send(false);
          }
          installStarted = true;
        } else if (stage == 'downloading') {
          if (downloadStarted) {
            console.log('Received multiple "downloading" stage events.');
            window.domAutomationController.send(false);
          }
          downloadStarted = true;
        } else {
          console.log('Received unknown install stage event: ' + stage);
          window.domAutomationController.send(false);
        }
      });
      chrome.webstore.install(
          undefined,
          function() {
            if (!downloadStarted || !installStarted) {
              console.log('Test Failed');
              if (!downloadStarted)
                console.log('Did not receive "downloading" event.');
              if (!installStarted)
                console.log('Did not receive "installing" event.');
              window.domAutomationController.send(false);
            }
            window.domAutomationController.send(true);
          },
          function(error) {
            console.log('Unexpected error: ' + error);
            window.domAutomationController.send(false);
          });
      // Force a garbage collection, so that if the callbacks aren't being
      // retained properly they'll get collected and the test will fail.
      window.gc();
    } catch (e) {
      console.log('Unexpected exception: ' + e);
      console.log(e.stack);
      window.domAutomationController.send(false);
      throw e;
    }
  }
</script>

</body>
</html>
